﻿using System;
using System.Collections.Generic;
using System.Windows.Browser;

namespace EasySL.Core
{
    public class Requestor
    {    
        public void GetDataAsync(Request request, Type type, Action<Response> callback)
        {                      
            string jsonString = request.Serialize();
            jsonString = HttpUtility.UrlEncode(jsonString);
            //jsonString = jsonString.Replace("+", "%2B");
            this.currentRequest = request;
            this.currentType = type;
            this.currentCallback = callback;

            HttpHelper helper = new HttpHelper(new Uri(requestHandleUrl), "POST",
                new KeyValuePair<string, string>("request", jsonString));
            helper.ResponseComplete += new HttpResponseCompleteEventHandler(helper_ResponseComplete);
            helper.Execute();
        }

        void helper_ResponseComplete(HttpResponseCompleteEventArgs e)
        {
            Response response = new Response();
            response.Deserialize(e.Response, this.currentType);

            if (OnResponse != null)
                OnResponse(response);

            if (this.currentCallback != null && response.Status == ResponseStatus.Success)
                currentCallback(response);
        }

        private static string GetServiceUrl(string url)
        {
            Uri uri = new Uri(HtmlPage.Document.DocumentUri, url);
            return uri.AbsoluteUri;
        }

        public static Action<Response> OnResponse;

        private static readonly string requestHandleUrl = GetServiceUrl("Service.ashx");
        private Type currentType;
        private Request currentRequest;
        private Action<Response> currentCallback;
    }
}
